Build a Library Management System Using HTML, CSS, and JavaScript (Source Code)

Faraz

By Faraz -

Learn how to develop a modern Library Management System using HTML, CSS, and JavaScript. Organize your book collection while mastering web development skills.


Build a Library Management System Using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

In the realm of modern libraries, efficient management and accessibility of resources are paramount. Enter the Library Management System - a digital solution that revolutionizes how libraries organize and offer access to their collections. In this comprehensive guide, we will walk you through the step-by-step process of creating your own Library Management System using the dynamic trio of web development: HTML, CSS, and JavaScript.

Whether you're an aspiring web developer looking to hone your skills or a librarian aiming to streamline library operations, this tutorial will equip you with the knowledge and tools to bring your vision to life. By the end of this journey, you'll not only grasp the fundamentals of web development but also contribute to the enhancement of library experiences in the digital age.

Join us as we embark on this coding adventure, combining creativity and functionality to craft a user-friendly interface, integrate interactive features, and design an organized book catalog. Let's dive into the world of HTML, CSS, and JavaScript to create a Library Management System that sets new standards in resource management and accessibility.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Library Management System.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code step by step:

1. <!DOCTYPE html>: This declares the document type and version of HTML being used (HTML5 in this case).

2. <html lang="en">: This is the root element of the HTML document. The lang attribute specifies the language of the document, which is English in this case.

3. <head>: This section contains metadata about the webpage, such as character encoding, viewport settings, and linked resources.

  • <meta charset="utf-8">: Specifies the character encoding for the document (UTF-8, which supports various characters and symbols).
  • <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">: Sets the viewport settings for better responsiveness on various devices.
  • <link rel="stylesheet" href="...">: Links an external stylesheet for styling the webpage. The stylesheet is fetched from a CDN (Content Delivery Network) and provides styles from the Bootstrap framework.
  • <title>Library Management System</title>: Sets the title of the webpage, which is displayed in the browser's title bar or tab.

4. <body>: This is the main content of the webpage.

5. <nav class="navbar">: Defines a navigation bar at the top of the page.

  • The brand name "Online Library" is displayed on the left side.
  • A "navbar-toggler" button is provided for small screens to collapse and expand the navigation links.
  • Navigation links include a "Home" link and a search form.

6. <div id="alertuser"></div>: A placeholder div element where alerts or notifications could be displayed later.

7. <div class="container">: Creates a container for the main content of the page.

  • Page heading "Welcome to My Library" is displayed.
  • A form labeled "mylibraryform" is provided for users to input information.
  • It includes fields for "User Name" and "Book Name," along with radio buttons for selecting a book genre ("Fiction," "Programming," "Cooking").
  • A button labeled "Add Book" is used to submit the form.
  • A table with a dark style is defined to display library records.
  • The table headers include "Sl No.," "Date of issue," "Reader," "Book Name," "Genre," and an empty header cell.
  • The table body has an empty tbody element with the id "table-body" where book records will be added later.

8. <script src="script.js"></script>: Links an external JavaScript file named "script.js" for adding dynamic behavior to the webpage.

9. Two more <script> elements link external JavaScript files from CDNs. These scripts provide functionality from the Bootstrap and jQuery libraries, enhancing interactivity and styling on the page.

This is the basic structure of our Library Management System using HTML, and next, we can proceed with its visual refinement using JavaScript.

Step 2 (CSS Code):

No custom CSS thanks to Bootstrap!

/*

 No custom CSS thanks to Bootstrap!
 https://getbootstrap.com/

*/ 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Here's an explanation of the code's functionality:

1. Function inputs(userName, bookName, type): This function defines a constructor for creating objects representing book inputs. It takes three parameters: userName (user's name), bookName (name of the book), and type (type of the book).

2. Class Display: This class contains methods to manage the display of book information and interact with the user interface.

  • constructor(): The class constructor, which is empty in this case.
  • add(arrayInputs): This method takes an array of book input objects as a parameter. It generates HTML rows for each input and appends them to a table in the UI.
  • clear(): This method clears the input fields in the form.
  • validate(inputs): This method validates whether the input fields are filled correctly (user name and book name are not empty).
  • alertuser(type, sub, massage): This method adds an alert message to the UI with a specified type (success, danger), subject, and message. The alert is automatically removed after 4 seconds.
  • checkIssue(listArray, o1): This method checks whether a book is already issued by searching the listArray of book inputs. If the book is issued, it returns 0; otherwise, it returns 1.

3. Function showList(): This function is responsible for displaying the list of books even after a page reload. It retrieves stored book inputs from local storage and uses the Display class to display them in the UI.

4. Function deleteItem(index): This function deletes a book entry from the list. It retrieves stored book inputs from local storage, removes the selected entry based on the provided index, updates local storage, and then calls showList() to refresh the UI.

5. Event listener for form submit: An event listener is attached to the form with the ID mylibraryform. When the form is submitted, the formSubmit function is triggered.

  • Inside formSubmit, the values from the input fields are extracted.
  • An inputs object is created from the extracted values.
  • An instance of the Display class is created.
  • The input is validated using the validate method, and then checked for existing issuance using the checkIssue method.
  • If validation passes and the book is not already issued, the input is added to the listArray, which is then updated in local storage and displayed using the Display class. A success alert is also shown.
  • If the book is already issued, an alert is shown indicating the issuing user.
  • If validation fails, a failure alert is shown.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

// getting input from input areas -->

function inputs(userName, bookName, type) {
  this.userName = userName;
  this.bookName = bookName;
  this.type = type;
}

class Display {
  constructor() {}
  add(arrayInputs) {
    let tableBody = document.getElementById("table-body");
    let today = new Date().toLocaleDateString();
    let htmltobeadded = "";
    for (let i = 0; i < arrayInputs.length; i++) {
      htmltobeadded += `
                  <tr>
                    <td>${i + 1}</td>
                    <td>${today}</td>
                    <td>${arrayInputs[i].userName}</td>
                    <td>${arrayInputs[i].bookName}</td>
                    <td>${arrayInputs[i].type}</td>
                    <td> <button type="button" onclick = "deleteItem(${i})" class ="dlt-btn btn-primary btn " id ="dlt-btn"> Delete </button> </td>
                  </tr>
              `;
    }
    tableBody.innerHTML = htmltobeadded;
  }
  clear() {
    let myForm = document.getElementById("mylibraryform");
    myForm.reset();
  }
  validate(inputs) {
    if (inputs.userName == "" || inputs.bookName == "") {
      return false;
    } else return true;
  }
  alertuser(type, sub, massage) {
    let alertuser = document.getElementById("alertuser");
    let htmltobeaddedinalert = ` <div class="alert alert-${type} alert-dismissible fade show" id="alert" role="alert" >
      <strong>${sub}</strong> ${massage}
      <button type="button" class="close"  data-dismiss="alert" aria-label="Close">
      
  <span aria-hidden="true">×</span>
      </button>
    </div>`;
    alertuser.innerHTML += htmltobeaddedinalert;
    setTimeout(() => {
      alertuser.innerHTML = "";
    }, 4000);
  }

  // check if the book is issued or not -->
  checkIssue(listArray, o1) {
    for (let i = 0; i < listArray.length; i++) {
      if (listArray[i].bookName == o1.bookName) {
          this.issuedUser = listArray[i].userName;
        return 0;
      }
    }
    return 1;
  }
}

// Show BookList even after reload -->
function showList() {
  let listItems = localStorage.getItem("listItems");
  if (listItems == null) {
    listArray = [];
  } else {
    listArray = JSON.parse(listItems);
  }
  new Display().add(listArray);
  // console.log(listArray);
}
showList();

// Deleting List Item -->
function deleteItem(index) {
  let listItems = localStorage.getItem("listItems");
  if (listItems == null) {
    listArray = [];
  } else {
    listArray = JSON.parse(listItems);
  }
  listArray.splice(index, 1);
  localStorage.setItem("listItems", JSON.stringify(listArray));
  showList();
}

// add submit finction to the form -->
const form = document.getElementById("mylibraryform");
form.addEventListener("submit", formSubmit);
function formSubmit(e) {
  e.preventDefault();
  let givenUserName = document.getElementById("User-Name").value;
  let givenBookName = document.getElementById("Book-Name").value;
  let givenType;
  let checkFiction = document.getElementById("Fiction");
  let checkPrograming = document.getElementById("Programing");
  let checkcooking = document.getElementById("Cooking");
  if (checkFiction.checked) {
    givenType = checkFiction.value;
  } else if (checkPrograming.checked) {
    givenType = checkPrograming.value;
  } else {
    givenType = checkcooking.value;
  }

  let o1 = new inputs(givenUserName, givenBookName, givenType);

  let displayObj = new Display();
  if (displayObj.validate(o1) && displayObj.checkIssue(listArray, o1) == 1) {
    let listItems = localStorage.getItem("listItems");
    if (listItems == null) {
      listArray = [];
    } else {
      listArray = JSON.parse(listItems);
    }
    listArray.push(o1);
    localStorage.setItem("listItems", JSON.stringify(listArray));
    // console.log(listArray.length);

    new Display().add(listArray);
    displayObj.clear();
    displayObj.alertuser("success", "Success", "Book is issued");
  } else if (displayObj.checkIssue(listArray, o1) == 0) {
      let issuedUser = 
    displayObj.alertuser(
      "danger",
      "Oops!",
      `Book is already issued by ${displayObj.issuedUser}`
    );
    displayObj.clear();
  } else {
    displayObj.alertuser("danger", "Oops!", "Book is not issued");
    displayObj.clear();
  }
}

Final Output:

Build a Library Management System Using HTML, CSS, and JavaScript.gif

See the Pen Untitled by Faraz (@codewithfaraz) on CodePen.

Conclusion:

As we wrap up our exploration into building a Library Management System using HTML, CSS, and JavaScript, we stand at the crossroads of traditional library management and digital innovation. Throughout this journey, we've delved into the core components that make up a functional and user-centric system, breathing new life into how libraries operate in the digital age.

But this guide is not just about crafting lines of code. It's about the intersection of technology and human interaction, where a Library Management System becomes a bridge that connects knowledge seekers with the vast treasure troves of information stored within the library's collection.

As you venture forward, armed with newfound skills and insights, remember that the journey doesn't end here. The world of web development is ever-evolving, and the possibilities are limitless. We encourage you to continue exploring, experimenting, and enhancing your system. Your creation has the potential to shape the way libraries function, making information more accessible and enjoyable for all.

Thank you for joining us on this coding odyssey. May your Library Management System be a beacon of efficiency, accessibility, and innovation in the world of libraries. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺